<?php
class CheckCode {
    private $width;
    private $height;
    private $img;
    private $codeLen = 4;
    private $codes = 'abcdefghijkmnpqrstuvwxyz23456789';
    public function __construct($width = 85, $height = 30) {
        $this->width = $width;
        $this->height = $height;
    }

    private function _createBg() {
        $this->img = imagecreatetruecolor($this->width, $this->height);
        $color = imagecolorallocate($this->img, 30, 30, 30);
        imagefill($this->img, 0, 0, $color);
    }

    private function _createCode() {
        for($i=0;$i<$this->codeLen;$i++) {
            $this->text .= $this->codes[mt_rand(0, strlen($this->codes)-1)];
        }
        $_SESSION['code'] = $this->text;
        for($i=0;$i<$this->codeLen;$i++) {
            $color = imagecolorallocate($this->img, mt_rand(60, 150) ,mt_rand(60, 150), mt_rand(60, 150));
            imagestring($this->img, 25, ($this->width/$this->codeLen)*($i+1)-15, 7, $this->text[$i], $color);
        }
    }

    public function output() {
        $this->_createBg();
        $this->_createCode();
        header('Content-type:image/png');
        imagepng($this->img);
        imagedestroy($this->img);
    }
}

?>